package com.whc.gulimall.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.constant.WareConstant;
import com.whc.common.utils.PageUtils;
import com.whc.common.utils.Query;
import com.whc.gulimall.ware.dao.PurchaseDao;
import com.whc.gulimall.ware.entity.PurchaseDetailEntity;
import com.whc.gulimall.ware.entity.PurchaseEntity;
import com.whc.gulimall.ware.entity.WareSkuEntity;
import com.whc.gulimall.ware.feign.SkuInfoFeignService;
import com.whc.gulimall.ware.service.PurchaseDetailService;
import com.whc.gulimall.ware.service.PurchaseService;
import com.whc.gulimall.ware.service.WareSkuService;
import com.whc.gulimall.ware.vo.MergeVo;
import com.whc.gulimall.ware.vo.PurchaseDoneVo;
import com.whc.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author angaoen
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    /**
     * 商品库存 Service
     */
    @Resource
    private WareSkuService wareSkuService;

    /**
     * gulimall-product->skuInfoController
     */
    @Resource
    private SkuInfoFeignService skuInfoFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @param params 分页条件
     * @return 分页数据
     */
    @Override
    public PageUtils listUnReceivePurchase(@RequestParam Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    /**
     * 合并采购项
     *
     * @param vo 数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void mergePurchase(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        // 新增
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 修改
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    /**
     * 领取采购项
     *
     * @param purchaseIds 采购单id列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receivePurchase(List<Long> purchaseIds) {
        if (CollUtil.isNotEmpty(purchaseIds)) {
            List<PurchaseEntity> purchaseEntities = this.listByIds(purchaseIds);
            // 过滤出新建和已分配的采购单并更新状态
            List<PurchaseEntity> receivePurchases = purchaseEntities.stream().filter(item ->
                            item.getStatus().equals(WareConstant.PurchaseStatusEnum.CREATED.getCode())
                                    || item.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                    .peek(item -> item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode()))
                    .collect(Collectors.toList());
            // 领取采购单
            this.updateBatchById(receivePurchases);

            //更新采购需求的状态
            // 获取已领取的采购单id列表
            List<Long> receivePurchaseIds = receivePurchases.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
            // 根据采购单列表修改采购需求状态
            purchaseDetailService.updateDetailsByReceivePurchaseIds(receivePurchaseIds);
        }
    }

    /**
     * 完成采购需求
     *
     * @param vo 数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void done(PurchaseDoneVo vo) {
        // 获取采购单id
        Long id = vo.getId();

        // 获取是否有异常的采购需求
        long count = vo.getItems().stream()
                .filter(item -> item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()))
                .count();
        // 有异常就设置采购单状态为有异常，没有就设置完成
        this.update(new UpdateWrapper<PurchaseEntity>()
                .set("status", count > 0
                        ? WareConstant.PurchaseStatusEnum.HASERROR.getCode()
                        : WareConstant.PurchaseStatusEnum.FINISH.getCode())
                .eq("id", id));

        // 设置采购需求
        List<PurchaseDetailEntity> itemList = vo.getItems().stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setPurchaseId(id);
            detailEntity.setId(item.getItemId());
            detailEntity.setStatus(item.getStatus());
            return detailEntity;
        }).collect(Collectors.toList());
        // 更新采购需求
        purchaseDetailService.updateBatchById(itemList);

        // 获取需求采购ids
        List<Long> itemIds = vo.getItems().stream().map(PurchaseItemDoneVo::getItemId).collect(Collectors.toList());
        // 获取到需求采购数据
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(itemIds);
        // 获取到skuIds列表
        List<Long> skuIds = purchaseDetailEntities.stream().map(PurchaseDetailEntity::getSkuId).distinct()
                .collect(Collectors.toList());
        // 调用远程接口获取sku名称
        String json = JSON.toJSONString(skuInfoFeignService.listSkuNamesBySkuIds(skuIds).get("data"));
        Map dataMap = JSON.parseObject(json, HashMap.class);

        // 判空
        if (CollUtil.isNotEmpty(purchaseDetailEntities)) {
            for (PurchaseDetailEntity entity : purchaseDetailEntities) {
                WareSkuEntity wareSkuEntity = wareSkuService.getOne(new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", entity.getSkuId())
                        .eq("ware_id", entity.getWareId()));
                if (wareSkuEntity != null) {
                    // 修改操作
                    wareSkuEntity.setStock(wareSkuEntity.getStock() + entity.getSkuNum());
                    wareSkuService.updateById(wareSkuEntity);
                } else {
                    // 保存操作
                    wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(entity.getSkuId());
                    wareSkuEntity.setWareId(entity.getWareId());
                    wareSkuEntity.setStock(entity.getSkuNum());
                    wareSkuEntity.setSkuName((String) dataMap.get(wareSkuEntity.getSkuId().toString()));
                    wareSkuService.save(wareSkuEntity);
                }
            }
        }
    }
}
